package web.staff;

import bean.Staff;
import bean.Type;
import com.alibaba.fastjson.JSON;
import entity.DepartmentEntity;
import entity.StaffEntity;
import entity.TypeEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "StaffEdit",urlPatterns = "/dao/update/staffEdit")
public class StaffEdit extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonString = FANREN.getJson(request);
        Staff staff = JSON.parseObject(jsonString,Staff.class);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        StaffEntity staffEntity = null;
        if(staff.getSid().equals("")) {
            //新增
            staffEntity = new StaffEntity();
        } else {
            //修改
            staffEntity = em.find(StaffEntity.class,Integer.parseInt(staff.getSid()));
        }
        staffEntity.setEmail(staff.getEmail());
        staffEntity.setName(staff.getName());
        staffEntity.setPhone(staff.getPhone());
        Query query = em.createNativeQuery("select did from DepartmentEntity where name = ?");
        query.setParameter(1, staff.getDepartment());
        List list = query.getResultList();
        DepartmentEntity departmentEntity = em.find(DepartmentEntity.class, list.get(0));
        staffEntity.setDid(departmentEntity);
        em.persist(staffEntity);
    }
}
